package com.ben.tcptester.web;

import com.ben.tcptester.Entity.Server;
import com.ben.tcptester.bean.AjaxBaseResponse;
import com.ben.tcptester.exception.ClientException;
import com.ben.tcptester.tcpclient.netty.ServerRepository;
import com.ben.tcptester.tcpclient.netty.TcpTesterClient;
import com.ben.tcptester.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Peter on 2017/7/5.
 */
@Controller
public class TcpTesterController {

    private static final Logger logger = LoggerFactory.getLogger(TcpTesterController.class);

    @RequestMapping(value = "/tcpTester")
    public String errorInfo() {
        return "tcpTester";
    }

    @RequestMapping(value = "/server/add")
    @ResponseBody
    public AjaxBaseResponse addServer(@ModelAttribute("server") Server server) {
        logger.info("inParams -->> " + JsonUtil.toJson(server));
        AjaxBaseResponse response = new AjaxBaseResponse();
        // 将server添加到容器
        try {
            ServerRepository.add(server.getId(), server);
        } catch (ClientException e) {
            e.printStackTrace();
            response.setSuccess(false);
            response.setMessage(e.getMessage());
        }
        response.setData(server);
        return response;
    }

    // 向一个Server添加一个客户端连接，可以添加多个客户端连接
    @RequestMapping(value = "/client/connect/{serverId}")
    @ResponseBody
    public AjaxBaseResponse connectToServer(@PathVariable("serverId") String serverId) {
        logger.info("inParams -->> serverId=" + serverId);
        AjaxBaseResponse response = new AjaxBaseResponse();

        boolean isConnected = false;
        try {
            Server srv = ServerRepository.get(serverId);
            if (srv == null) {
                response.setMessage("The Server is not exists for id=" + serverId);
            } else {
                TcpTesterClient tcpTesterClient = new TcpTesterClient(srv);
                tcpTesterClient.start();
                isConnected = true;
            }
        } catch (Exception e) {
            response.setMessage(e.getMessage());
        }
        response.setSuccess(isConnected);
        return response;
    }

    @RequestMapping(value = "/client/disconnect/{serverId}/{clientId}")
    @ResponseBody
    public AjaxBaseResponse disconnectToServer(@PathVariable("serverId") String serverId, @PathVariable("clientId") String clientId) {
        logger.info("inParams -->> clientId=" + clientId);
        AjaxBaseResponse response = new AjaxBaseResponse();

        boolean isConnected = false;
        try {
            Server srv = ServerRepository.get(serverId);
            if (srv == null) {
                response.setMessage("The Server is not exists for id=" + serverId);
            } else {
                srv.disconnect(clientId);
                isConnected = true;
            }
        } catch (ClientException e) {
            response.setSuccess(false);
            response.setMessage(e.getMessage());
        } catch (Exception e) {
            response.setMessage(e.getMessage());
        }
        response.setSuccess(isConnected);
        return response;
    }

    @RequestMapping(value = "/server/send")
    @ResponseBody
    public AjaxBaseResponse sendToServer(@RequestParam("data") String data, @RequestParam("serverId") String serverId) {
        logger.info("inParams -->> serverId=" + serverId + ",data=" + data);
        AjaxBaseResponse response = new AjaxBaseResponse();

        try {
            Server srv = ServerRepository.get(serverId);
            if (srv == null) {
                response.setMessage("The Server is not exists for id=" + serverId);
                response.setSuccess(false);
            } else {
                srv.send(data);
                response.setSuccess(true);
            }
        } catch (ClientException e) {
            response.setSuccess(false);
            response.setMessage(e.getMessage());
        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage(e.getMessage());
        }
        return response;
    }


}
